var express = require('express');
var formidable = require('formidable');
var path = require('path');
var fs = require('fs');
var uuid = require('uuid');
var router = express.Router();


const Query = require("../tools/db")
const { verifyToken } = require("../config/config");
const { extname } = require('path');


// 头像上传
router.post("/uploadhead", (req, res, next) => {

  // 个人中心、头像上传时需要权限的，所以先验证一下权限（token）
  // 假设已经接收到前端传递过来的token
  // let [err,user]=verifyToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImJiIiwibWlkIjoiOTgyZmEzZjctMDkxMS00ZGFlLWFlZDAtZGIzYTY2ZWEyZGIzIiwiaWF0IjoxNjUwNDE2MjE3LCJleHAiOjE2NTA0MTk4MTd9.N3hqa3D9OhLbSUDp0CRvjbf_mL50MGYaWLqKtmG_51w")
  let [err, user] = verifyToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImJiIiwibWlkIjoiOTgyZmEzZjctMDkxMS00ZGFlLWFlZDAtZGIzYTY2ZWEyZGIzIiwiaWF0IjoxNjUwNDE5OTY1LCJleHAiOjE2NTA0MjM1NjV9.yN5wpKXcDTzNQ848z20aC7mGn-7OKVozKru4sQ5dln0")

  // console.log(err,mid);
  if (err) {
    next("请重新登录")
    return
  }

  let {mid}=user




  // 执行文件上传
  // 设置临时上传目录
  let form=formidable({
    uploadDir: path.join(__dirname,"../tempdir")
  })


  // 解析文件上传信息
  form.parse( req ,async (err,fields,files)=>{
   
    // 把tempdir中的文件放到uploads
    // 旧路径
    let oldpath=files.touxiang.filepath
    // 新文件名称
    let newname= uuid.v4()
    // 扩展名
    let extname= path.extname(files.touxiang.originalFilename)
    // 新文件名
    let newfilename= newname+ extname
    // 新路径
    let newpath=path.join(__dirname,"../uploads","./head",  newfilename )
    
    fs.renameSync(oldpath,newpath)


    // 修改数据库
    let sql=`update e_member set head_photo_url="${newfilename}" where mid="${mid}"`
    let [err1,result ]=await Query(sql)

    if(err1){
      next("服务器出问题了，请稍后再试")
      return
    }


    res.send({
      status:200,
      msg:"头像更新成功",
      url:newpath
    })

  }  )







})




module.exports = router;
